package com.md.config.aliyun.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author 刘骄阳
 * 2023-08-08 15:28
 */
@Component
@RequiredArgsConstructor
public class SmsClient {
  private final SmsConfig config;

  public static Client createClient(final String accessKeyId, final String accessKeySecret, final String endpoint,
                                    final String regionId) throws Exception {
    // 访问的域名
    return new Client(new Config().setAccessKeyId(accessKeyId)
      .setAccessKeySecret(accessKeySecret).setEndpoint(endpoint).setRegionId(regionId));
  }

  /**
   * 使用AK&SK初始化账号Client
   *
   * @return Client
   * @throws Exception Exception
   */
  public Client createClient(final String key) throws Exception {
    SmsConfig smsConfig = getSmsConfig(key);
    // 访问的域名
    return createClient(smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret(), smsConfig.getEndpoint(),
      smsConfig.getRegionId());
  }

  /**
   * 根据key获取sms配置
   *
   * @param key key
   * @return SmsConfig
   */
  public SmsConfig getSmsConfig(final String key) {
    return config.getSmsConfigMap().getOrDefault(key, config);
  }

}
